import 'dart:io';
import 'package:ease_call_kit/ease_call_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hx_im_plugin/hx_im_plugin.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_face_view.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_input_bar.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_items/hq_chat_voice_record_animated.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_more_view.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_items/hq_chat_item.dart';
import 'package:hx_im_plugin_example/hq_im_ui/utils/envent_bus.dart';
import 'package:hx_im_plugin_example/hq_im_ui/utils/hq_chat_voice_player.dart';
import 'package:hx_im_plugin_example/hq_im_ui/utils/im_helper.dart';
import 'package:hx_im_plugin_example/hq_im_ui/widgets/hq_app_bar.dart';
import 'package:hx_im_plugin_example/hq_im_ui/widgets/hq_common_widgets.dart';
import 'package:hx_im_plugin_example/hq_im_ui/widgets/hq_show_large_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';
import 'package:provider/provider.dart';
import 'package:record_amr/record_amr.dart';

bool isShowQuickMenu = false; /// 底部快捷键菜单<单聊true；群聊false>

class HQChatPage extends StatefulWidget {

  final String titleStr;
  final EMConversation conv;
  HQChatPage(
    this.titleStr,
    EMConversation conversation
  ) : conv = conversation;

  @override
  _HQChatPageState createState() => _HQChatPageState();
}

class _HQChatPageState extends State<HQChatPage> implements HqChatInputBarListener, EMChatManagerListener, EMChatRoomEventListener, EaseCallKitListener {

  /// 时间显示间隔为1分钟
  final int _timeInterval = 60 * 1000;
  /// 用来决定是否显示时间
  int _adjacentTime = 0;
  HqChatVoicePlayer _voicePlayer = HqChatVoicePlayer();
  final _scrollController = ScrollController();
  /// 输入
  HqChatInputBar _inputBar;
  HqChatInputBarType _inputBarType = HqChatInputBarType.hq_normal;
  TextEditingController _inputBarEditingController = TextEditingController();
  int _subscribeId;
  bool _keyboardVisible = false;
  /// "+"更多
  List<HqChatMoreViewItem> _items;
  HqChatMoreView _moreView;
  /// 消息List
  List<EMMessage> _msgList = List();

  /// 录制语音动画
  HqChatVoiceRecordAnimated _voiceRecordAnimated = HqChatVoiceRecordAnimated();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _initEvents();

    EaseCallKit.listener = this;
    /// 监听键盘弹起收回
    _subscribeId = KeyboardVisibilityNotification().addNewListener(
      onChange: (bool visible) {
        _keyboardVisible = visible;
        _setStateAndMoreToListViewEnd();
      },
    );

    /// 初始化more
    _items = [
      HqChatMoreViewItem('images/chat_input_more_photo.png', '相册', _moreViewPhotoBtnOnTap),
      HqChatMoreViewItem('images/chat_input_more_camera.png', '相机', _moreCameraBtnOnTap),
      // HqChatMoreViewItem('images/chat_input_more_loc.png', '位置', _moreLocalBtnOnTap)
    ];
    _moreView = HqChatMoreView(_items);

    /// 添加环信回调监听
    EMClient.getInstance.chatManager.addListener(this);
    EMClient.getInstance.chatRoomManager.addChatRoomChangeListener(this);
    /// 设置所有消息已读
    widget.conv?.markAllMessagesAsRead();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.minScrollExtent) {
      }
    });

    if (widget.conv?.type == EMConversationType.ChatRoom) {
      EMClient.getInstance.chatRoomManager.joinChatRoom(widget.conv?.id).then((value) => _loadMessages());
    } else {
      _loadMessages();
    }

  }

  @override
  void dispose() {
    /// 移除键盘监听
    KeyboardVisibilityNotification().removeListener(_subscribeId);
    /// 移除环信回调监听
    EMClient.getInstance.chatManager.removeListener(this);
    _scrollController.dispose();
    _inputBarEditingController.dispose();
    if (widget.conv?.type == EMConversationType.ChatRoom) {
      EMClient.getInstance.chatRoomManager.leaveChatRoom(widget.conv?.id);
    }
    EaseCallKit.dispose();
    bus.off('updateCustomMessage');
    super.dispose();
  }

  _initEvents() {
    bus.on('updateCustomMessage', (res) {
      print('更新消息');
      if (res) {
        _loadMessages();
      }
    });
  }

  _getGroupInfo(String std) async {
    if (std.length == 0) return;
    try {
      EMGroup group = await EMClient.getInstance.groupManager.getGroupSpecificationFromServer(std);
      Navigator.of(context).pushNamed('/groupInfo', arguments: group).then((value) {});
    } on EMError catch (e) {
    } finally {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {

    /// 初始化输入
    _inputBar = HqChatInputBar(
      listener: this,
      barType: _inputBarType,
      textController: _inputBarEditingController,
      isShowQuickMenu: isShowQuickMenu
    );

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: HqAppBar(
        widget.titleStr,
        rightWidgets: [
          widget.conv.type == EMConversationType.Chat ? Container() :
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () async {
              _getGroupInfo(widget.conv.id);
            },
          )
        ],
      ),
      body: GestureDetector(
        onTap: () {
          if (_keyboardVisible) {
            _inputBarType = HqChatInputBarType.hq_normal;
            SystemChannels.textInput.invokeMethod('TextInput.hide');
            setState(() {});
          }
        },
        child: SafeArea(
          child: Stack(
            children: [
              Column(
                children: [
                  /// 展示成员列表，打开下面代码
                  // widget.conv.type == EMConversationType.Chat ? Container() :
                  // HqGroupMembersMenu(widget.conv),

                  // Expanded(child: HqChatVoiceRecordAnimated(),),

                  /// 消息展示区
                  Flexible(
                    child: Container(
                      color: Color.fromRGBO(244, 244, 244, 1.0),
                      child: Builder(builder: (context) {
                        return CustomScrollView(
                          controller: _scrollController,
                          slivers: [
                            SliverList(
                              delegate: SliverChildBuilderDelegate(
                                      (_, int index) {
                                    return ChangeNotifierProvider<HqChatVoicePlayer>.value(
                                      value: _voicePlayer,
                                      child: _chatItemFromMessage(_msgList[index], index),
                                    );
                                  },
                                  childCount: _msgList.length
                              ),
                            )
                          ],
                        );
                      }),
                    ),
                  ),

                  /// 间隔线
                  Divider(height: 1.0),

                  /// 输入框
                  Container(
                    /// 限制输入框高度
                    constraints: BoxConstraints(
                      maxHeight: sHeight(90),
                      minHeight: sHeight(44),
                    ),
                    decoration: BoxDecoration(
                      color: Theme.of(context).cardColor,
                    ),
                    child: _inputBar,
                  ),

                  /// 输入框下部分View
                  _bottomWidget()
                ],
              ),
              Positioned(
                child: Center(
                  child: _voiceRecordAnimated,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  /// 返回消息item
  _chatItemFromMessage(EMMessage msg, int index) {
    _makeMessageAsRead(msg);
    bool needShowTime = false;
    if (_adjacentTime == 0 || (msg.serverTime - _adjacentTime).abs() > _timeInterval || index == 0) {
      needShowTime = true;
    }

    _adjacentTime = msg.serverTime;

    List<Widget> widgetsList = List();

    if (needShowTime) {
      widgetsList.add(
        Container(
          margin: EdgeInsets.only(top: sHeight(10)),
          child: Text(
            timeStrByMs(msg.serverTime, showTime: true),
            style: TextStyle(color: Colors.grey),
          ),
        ),
      );
    }

    widgetsList.add(
      Container(
        constraints: BoxConstraints(
          minWidth: double.infinity,
        ),
        child: HqChatItem(
          msg,
          widget.conv,
          onTap: (message) => _messageBubbleOnTap(message),
          errorBtnOnTap: (message) => _resendMessage(message),
          longPress: (message, value) => _messageOnLongPress(message, value),
        ),
        margin: EdgeInsets.only(
          top: sHeight(20),
          bottom: sHeight(20),
        ),
      ),
    );
    return Column(
      children: widgetsList,
    );
  }

  /// 发送消息已读回执
  _makeMessageAsRead(EMMessage msg) async {
    if (msg.chatType == EMMessageChatType.Chat && msg.direction == EMMessageDirection.RECEIVE) {
      if (msg.hasReadAck == false) {
        try {
          await EMClient.getInstance.chatManager.sendMessageReadAck(msg);
        } on EMError {}
      }
      if (msg.hasRead == false) {
        try {
          await widget.conv.markMessageAsRead(msg.msgId);
        } on EMError {}
      }
    }
  }

  /// 输入框下部分View
  _bottomWidget() {
    if (_inputBarType == HqChatInputBarType.hq_more) {
      return _moreView;
    } else if (_inputBarType == HqChatInputBarType.hq_emoji) {
      return HqChatFaceView(
        _inputBarEditingController.text.length > 0,
        onFaceTap: (expression) {
          _inputBarEditingController.text = _inputBarEditingController.text + '[${expression.name}]';
          setState(() {});
        },
        onDeleteTap: () {
          if (_inputBarEditingController.text.length > 0) {
            _inputBarEditingController.text = _inputBarEditingController.text.substring(0, _inputBarEditingController.text.length - 1);
          }
        },
        onSendTap: () => _sendTextMessage(_inputBarEditingController.text),
      );
    } else {
      return Container();
    }
  }

  /// 下拉加载更多消息
  _loadMessages({int count = 20, bool moveBottom = true}) async {
    _msgList = [];
    try {
      // IMHelper.insertCustomMessage(widget.conv);
      List<EMMessage> msgs = await widget.conv.loadMessages(startMsgId: _msgList.length > 0 ? _msgList.first.msgId : '', loadCount: count);
      _msgList.insertAll(0, msgs);
    } on EMError {} finally {
      if (moveBottom) {
        _setStateAndMoreToListViewEnd();
      } else {
        setState(() {});
      }
    }
  }

  /// 刷新View并滑动到最底部
  _setStateAndMoreToListViewEnd() {
    setState(() {});
    Future.delayed(Duration(milliseconds: 100), () {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }


///  ==== faceview 事件处理

  /// 点击bubble
  _messageBubbleOnTap(EMMessage msg) async {
    switch (msg.body.type) {
      case EMMessageBodyType.TXT:
        break;
      case EMMessageBodyType.IMAGE:
        {
          EMImageMessageBody body = msg.body as EMImageMessageBody;
          Image img;
          if (body.fileStatus != EMDownloadStatus.SUCCESS) {
            img = Image.network(
              body.remotePath,
              fit: BoxFit.cover,
            );
          } else {
            img = Image.file(
              File(body.localPath),
              fit: BoxFit.cover,
            );
          }
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (_) {
                return HqShowLargeImage(img);
              },
            ),
          );
        }
        break;
      case EMMessageBodyType.VOICE:
        {
          if (_voicePlayer.currentMsgId == msg.msgId) {
            _voicePlayer.stopPlay();
          } else {
            _voicePlayer.playVoice(msg);
          }
        }
        break;
      case EMMessageBodyType.VIDEO:
        break;
      case EMMessageBodyType.LOCATION:
        break;
      case EMMessageBodyType.FILE:
        break;
      case EMMessageBodyType.CMD:
        break;
      case EMMessageBodyType.CUSTOM:
        break;
    }
  }

  /// 消息长按
  _messageOnLongPress(EMMessage msg, String value) async {

    if (value == '复制') { /// 复制
      EMTextMessageBody body = msg.body;
      SmartDialog.showToast('复制成功', alignment: Alignment.center);
      Clipboard.setData(ClipboardData(text: body.content));

    } else if (value == '转发') { /// 转发
      Navigator.of(context).pushNamed('/contactSelect').then(
            (value) {
          if(value != null) {
            List<String> users = value as List<String>;
            if (users.length > 0) {
              IMHelper.forwardMessage(msg, users);
            }
          }
        },
      );
    } else if (value == '删除') { /// 删除
      try {
        /// 删除会话中所有消息
        bool isDelete = await widget.conv.deleteMessage(msg.msgId);
        if (isDelete) { bus.emit('updateCustomMessage', true); }
      } on EMError catch (e) {
        print('操作失败，原因是: $e');
      }

    } else if (value == '撤回') { /// 撤回
      EMClient.getInstance.chatManager.recallMessage(msg.msgId).then((value) => print(value)).catchError((e) => print(e));
    }
  }

  /// 发送文字消息
  _sendTextMessage(String txt) {
    if (txt.length == 0) return;
    EMMessage msg = EMMessage.createTxtSendMessage(
      widget.conv.id,
      content: txt,
    );
    _sendMessage(msg);
    _inputBarEditingController.text = '';
  }

  /// 发送图片消息
  _sendImageMessage(String imagePath, [String fileName = '']) {
    Image.file(
      File(imagePath),
      fit: BoxFit.contain,
    ).image.resolve(ImageConfiguration()).addListener(ImageStreamListener((ImageInfo info, bool _) {
      EMMessage msg = EMMessage.createImageSendMessage(
        widget.conv.id,
       imagePath,
        displayName: fileName,
      );
      EMImageMessageBody body = msg.body;
      body.height = info.image.height.toDouble();
      body.width = info.image.width.toDouble();
      msg.body = body;
      _sendMessage(msg);
    }));
  }

  /// 发消息方法
  _sendMessage(EMMessage msg) async {
    _chatType() {
      EMMessageChatType type = EMMessageChatType.Chat;
      switch (widget.conv.type) {
        case EMConversationType.Chat:
          type = EMMessageChatType.Chat;
          break;
        case EMConversationType.ChatRoom:
          type = EMMessageChatType.ChatRoom;
          break;
        case EMConversationType.GroupChat:
          type = EMMessageChatType.GroupChat;
          break;
        default:
      }
      return type;
    }

    msg.chatType = _chatType();
    EMMessage message = await EMClient.getInstance.chatManager.sendMessage(msg);
    _msgList.add(message);
    _setStateAndMoreToListViewEnd();
  }

  /// 重发消息
  void _resendMessage(EMMessage msg) async {
    // _msgList.remove(msg);
    await EMClient.getInstance.chatManager.resendMessage(msg);
    // _msgList.add(msg);
    _setStateAndMoreToListViewEnd();
  }

///  ==== moreview 事件处理

  /// 相册按钮被点击
  _moreViewPhotoBtnOnTap() async {
    PickedFile pickedFile = await ImagePicker().getImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      _sendImageMessage(
        pickedFile.path,
      );
      print('_moreViewPhotoBtnOnTap');
    }
  }

  /// 拍照按钮被点击
  _moreCameraBtnOnTap() {
    print('_moreCameraBtnOnTap');
  }

  /// 位置按钮被点击
  _moreLocalBtnOnTap() {
    print('_moreLocalBtnOnTap');
  }

  /// 文件按钮被点击
  _moreFileBtnOnTap() async {
    print('_moreFileBtnOnTap');
  }

  /// 大头针按钮被点击
  _moreVoiceCallBtnOnTap() {
    if (widget.conv.type == EMConversationType.Chat) {
      EaseCallKit.startSingleCall(widget.conv.id);
    }
  }

  _moreVideoCallBtnOnTap() {
    if (widget.conv.type == EMConversationType.Chat) {
      EaseCallKit.startSingleCall(widget.conv.id, callType: EaseCallType.SingeVideo);
    }
  }


///  ==== HqChatInputBarListener 监听处理

  @override
  void voiceBtnDragInside() {
    print('录音按钮内部');
  }

  @override
  void voiceBtnDragOutside() {
    print('录音按钮外部');
  }

  @override
  void voiceBtnTouchDown() {
    RecordAmr.startVoiceRecord((volume) {
      print('volume -- $volume');
    }).then((value) {
      if (value) {
        print('录制开始');
      } else {
        print('录制失败');
      }
    });
  }

  @override
  void voiceBtnTouchUpInside() {
    RecordAmr.stopVoiceRecord((path, duration) {
      if (path != null && duration > 0) {
        EMMessage msg = EMMessage.createVoiceSendMessage(widget.conv.id, path, duration: duration);
        _sendMessage(msg);
      } else {
        print('录制时间太短');
      }
    });
  }

  @override
  void voiceBtnTouchUpOutside() {
    print('录音按钮被外部抬起');
    _setStateAndMoreToListViewEnd();
  }

  @override
  void emojiBtnOnTap() {
    if (_inputBarType == HqChatInputBarType.hq_emoji) {
      _inputBarType = HqChatInputBarType.hq_input;
    } else {
      _inputBarType = HqChatInputBarType.hq_emoji;
    }
    _setStateAndMoreToListViewEnd();
  }

  @override
  void moreBtnOnTap() {
    if (_inputBarType == HqChatInputBarType.hq_more) {
      _inputBarType = HqChatInputBarType.hq_input;
    } else {
      _inputBarType = HqChatInputBarType.hq_more;
    }
    _setStateAndMoreToListViewEnd();
  }

  @override
  void textFieldOnTap() {
    _inputBarType = HqChatInputBarType.hq_input;
    _setStateAndMoreToListViewEnd();
  }

  @override
  void recordOrTextBtnOnTap({bool isRecord = false}) {
    if (_inputBarType == HqChatInputBarType.hq_normal) {
      _inputBarType = HqChatInputBarType.hq_input;
    } else {
      _inputBarType = HqChatInputBarType.hq_normal;
    }

    _setStateAndMoreToListViewEnd();
  }

  @override
  void sendBtnOnTap(String str) => _sendTextMessage(str);

  @override
  onCmdMessagesReceived(List<EMMessage> messages) {}

  @override
  onMessagesDelivered(List<EMMessage> messages) {}

  @override
  onMessagesRead(List<EMMessage> messages) {}

  @override
  onMessagesRecalled(List<EMMessage> messages) {}

  @override
  onMessagesReceived(List<EMMessage> messages) {
    for (var msg in messages) {
      if (msg.conversationId == widget.conv.id) {
        _msgList.add(msg);
      }
    }
    _setStateAndMoreToListViewEnd();
  }

  @override
  onConversationsUpdate() {}

  @override
  onConversationRead(String from, String to) {}

  @override
  void onAdminAdded(String roomId, String admin) {}

  @override
  void onAdminRemoved(String roomId, String admin) {}

  @override
  void onAnnouncementChanged(String roomId, String announcement) {}

  @override
  void onChatRoomDestroyed(String roomId, String roomName) {
    print('聊天室解散 -- $roomId, $roomName');
  }

  @override
  void onMemberExited(String roomId, String roomName, String participant) {}

  @override
  void onMemberJoined(String roomId, String participant) {}

  @override
  void onMuteListAdded(String roomId, List mutes, String expireTime) {}

  @override
  void onMuteListRemoved(String roomId, List mutes) {}

  @override
  void onOwnerChanged(String roomId, String newOwner, String oldOwner) {}

  @override
  void onRemovedFromChatRoom(String roomId, String roomName, String participant) {}

  @override
  void callDidEnd(String channelName, EaseCallEndReason reason, int time, EaseCallType callType) {}

  @override
  void callDidOccurError(EaseCallError error) {
    print('call error --- $error');
  }

  @override
  void callDidReceive(EaseCallType callType, String inviter, Map ext) {}

  @override
  void callDidRequestRTCToken(String appId, String channelName, String account) {}

  @override
  void multiCallDidInviting(List<String> excludeUsers, Map ext) {}

}
